package com.spddr.pmos.rpt.impl;

import java.util.List;
import java.util.stream.Collectors;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Period;
import org.joda.time.Years;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.spddr.pmos.domain.Metrics;
import com.spddr.pmos.rpt.RptReservoirForecast;
import com.spddr.pmos.rpt.pojo.CellValue;

import cn.seqdata.echarts.Option;
import cn.seqdata.echarts.VisualMap;
import cn.seqdata.echarts.axis.CategoryAxis;
import cn.seqdata.echarts.axis.ValueAxis;
import cn.seqdata.echarts.data.Data;
import cn.seqdata.echarts.series.Line;
import cn.seqdata.tags.Point;
import cn.seqdata.tags.common.IdTags;

@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class RptReservoirForecastImpl extends AbstractPivotChartImpl implements RptReservoirForecast {

	String[][] seasones = { { "丰水期", "06-01", "11-01" }, { "枯水期", "01-01", "04-30" }, { "枯水期", "12-01", "12-31" } };

	protected Period intervalOfStorage() {
		return Days.ONE.toPeriod();
	}

	@Override
	public List<CellValue> loadPivot() {
		metric = Metrics.FLOW_IN.name;
		Point<IdTags> point = new Point<>(metric, new IdTags(id));
		return sim(1).getValue().getValues().stream().map(v -> new CellValue(point, v, null, null))
				.collect(Collectors.toList());
	}

	@Override
	public Option chart() {
		Option option = new Option();

		CategoryAxis xAxis = new CategoryAxis().show(true);
		xAxis.setFunc(String.format("Admin.Array.dates(1, 'm-d', '%1$s', '%2$s')", getStartTime(), getEndTime()));
		option.xAxis(xAxis);

		option.yAxis(new ValueAxis().show(true));

		// 预测虚线
		Days days = Days.daysBetween(getStartTime(), DateTime.now().withTimeAtStartOfDay());
		if (0 < days.getDays()) {
			Data[] datas = { new Data().max(days.getDays()).color("red"),
					new Data().min(days.getDays()).color("gray").colorAlpha(0.2) };
			option.visualMapNew().show(false).dimension(0).pieces(datas);
		}
		Line line = new Line();
		// markArea
		if (Years.ONE.toPeriod().equals(interval)) {
			for (String[] season : seasones) {
				line.markArea().silent(true).data(
						Lists.newArrayList(new Data(season[0]).xAxis(season[1]), new Data(season[0]).xAxis(season[2])));
			}
		}
		// 数据
		sim(1).getValue().getValues().forEach(x -> {
			line.data().add(String.format("%.2f", x.getValue()));
		});
		option.series().add(line);
		return option;
	}

}
